package com.we.risk.phoneRecord.stage2.dimphone;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.we.risk.phoneRecord.common.PhoneRecordDataUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class DimPhoneRecordLabelCompare {
    public static final String RELEASEPROP =
            "risk/phonerecord/stage2/dim_phone_kfk_self_test.properties";
    public static final String PROPSETS = "risk/phonerecord/phonerecord.properties";
    public static Logger LOG = LoggerFactory.getLogger(DimPhoneRecordLabelCompare.class);

    public static final String MOBILE_AREA_BROADCAST_DESC = "phonerecord_mob_area_broad_cast_desc";
    public static final int MOBILE_AREA_BROADCAST_WAIT_SEC = 15 * 1000;
    public static final String SPLITWORD = "#";
    public static final String DATEFORMAT = "yyyy-MM-dd";
    public static final String MSGTYPE = "HFQ_UPLOAD_PHONE_CALL_RECORD";
    public static final String INPUTKEYBY = "userKey";
    public static final String OUTPUTKEY = "user_key";
    public static final String TIMESTAMP = "timestamp";
    public static final String JOBID = "jobID";
    public static final String PHONECALLLIST = "phoneCallList";
    public static final String REMOVEJSONKEY = "numberType";
    public static final Long KFKMSGMAXSIZE = 20 * 1024 * 1024L;

    public static void main(String[] args) throws IOException {
        try {
            //           File input = new
            // File("/Users/jk/Downloads/风控实时标签需求/通话记录-loulingbo/ExceptionLog/error.json");
            File input =
                    new File(
                            "/Users/jk/Downloads/风控标签需求/实时需求/通话记录-loulingbo/Stage3/cmp/09dc1403a4edc2b4fd100efca0ebb834.json");
            File sgTag =
                    new File(
                            "/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/risk_phone_record_sougou_cuishou_tag_all_jkuse.txt");
            //           File mobArea = new
            // File("/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/mobile_area.data");
            File mobData =
                    new File(
                            "/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/mobile_data_hive_udf.data");
            File v1Clean =
                    new File(
                            "/Users/jk/Downloads/AAAAAAARzSz/UserLabelPlatform/14.4/llb_reg_address_level_v1_clean_jkuse.txt");
            File outfile =
                    new File(
                            "/Users/jk/Downloads/风控实时标签需求/通话记录-loulingbo/data_compare/1106/phone_compare.data");

            HashMap<String, String> sgMap = initSgCsTagMap(sgTag);
            HashMap<String, String> v1CleanMap = initV1CleanMap(v1Clean);
            HashMap<String, String> mobAreaMap = initMobAreaMap(mobData);

            String inputStr = FileUtils.readFileToString(input);
            JSONObject inputJson = JSONObject.parseObject(inputStr);

            if (inputJson != null && inputJson.getString("type").equals(MSGTYPE)) {
                JSONObject dataJson = inputJson.getJSONObject("dataJson");
                Long captureTime = dataJson.getLong(TIMESTAMP);
                JSONObject job = dataJson.getJSONObject("job");
                String jobID = job.getString(JOBID);

                String userKey = dataJson.getString(INPUTKEYBY);
                JSONObject data = dataJson.getJSONObject("data");
                JSONArray calls = data.getJSONArray(PHONECALLLIST);
                JSONObject outJson = new JSONObject();

                if (userKey != null) {
                    outJson.put(OUTPUTKEY, userKey);
                    outJson.put(TIMESTAMP, captureTime);
                    outJson.put(JOBID, jobID);
                    outJson.put(PHONECALLLIST, calls);

                    ProcessData(outJson, sgMap, v1CleanMap, mobAreaMap);
                }
                FileUtils.writeStringToFile(outfile, outJson.toString());
            }

        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            LOG.error("Exception: " + e.toString());
            e.printStackTrace();
        }
    }

    private static HashMap<String, String> initV1CleanMap(File mobAreaFile) throws IOException {
        List<String> v1CleanLines = FileUtils.readLines(mobAreaFile);
        HashMap<String, String> mobMap = new HashMap<>();
        for (String line : v1CleanLines) {
            String[] splits = line.split(",");
            if (splits.length == 4) {
                String new_prov = splits[0];
                String new_city = splits[1];
                String raw_prov = splits[2];
                String raw_city = splits[3];
                String mapKey = raw_prov + SPLITWORD + raw_city;
                String mapVal = new_prov + SPLITWORD + new_city;
                mobMap.put(mapKey, mapVal);
            } else {
                LOG.error("DimPhoneRecordLabel initV1CleanMap error read line: " + line);
            }
        }
        return mobMap;
    }

    private static HashMap<String, String> initSgCsTagMap(File sgTagFile) throws IOException {
        HashMap<String, String> sgMap = new HashMap<>();
        List<String> sgTagLines = FileUtils.readLines(sgTagFile);
        for (String line : sgTagLines) {
            String[] splits = line.split(",");
            if (splits.length == 3) {
                String phone_num = splits[0];
                String sgTag = splits[1];
                String coName = splits[2];
                String mapKey = phone_num;
                String mapVal = sgTag + SPLITWORD + coName;
                sgMap.put(mapKey, mapVal);
            } else {
                LOG.error("DimPhoneRecordLabel initSgCsTagMap error read line: " + line);
            }
        }
        return sgMap;
    }

    private static HashMap<String, String> initMobAreaMap(File mobArea) throws Exception {
        {
            HashMap<String, String> mobAreaMap = new HashMap<>();
            List<String> sgTagLines = FileUtils.readLines(mobArea);
            for (String line : sgTagLines) {
                String[] splits = line.split(",");
                if (splits.length == 3) {
                    String mobile = splits[0];
                    String province = splits[1];
                    String city = splits[2];
                    if (province == null || province.equals("")) {
                        province = "null";
                    }

                    if (city == null || city.equals("")) {
                        city = "null";
                    }
                    mobAreaMap.put(mobile, province + SPLITWORD + city);
                } else {
                    LOG.error("DimPhoneRecordLabel initMobAreaMap error read line: " + line);
                }
            }
            return mobAreaMap;
        }
    }

    private static String[] MapMobArea(
            String mobile, HashMap<String, String> mobAreaMap, HashMap<String, String> v1CleanMap)
            throws Exception {
        String res = mobAreaMap.get(mobile);
        String[] newAddrs = new String[2];
        if (res != null) {
            LOG.debug("MapMobArea get res: " + res);
            String[] splits = res.split(SPLITWORD);
            if (splits.length == 2) {
                String mob_prov = (splits[0].equals("null") ? "" : splits[0]);
                String mob_city = (splits[1].equals("null") ? "" : splits[1]);

                String trans_key = mob_prov + SPLITWORD + mob_city;
                String trans_val = v1CleanMap.get(trans_key);
                LOG.debug("MapMobArea get trans_val: " + trans_val);
                if (trans_val != null) {
                    newAddrs = trans_val.split(SPLITWORD);
                    if (newAddrs.length == 2) {
                        LOG.debug("MapMobArea get prov: " + newAddrs[0] + " city: " + newAddrs[1]);
                        return newAddrs;
                    } else {
                        LOG.warn("DimPhoneRecordLabel MapMobArea V1Clean data error: " + trans_val);
                    }
                } else {
                    LOG.warn("DimPhoneRecordLabel MapMobArea err trans_key: " + trans_key);
                }

                //                    LOG.warn("Debug UserJoinMobileAreaProcessFunc ProcessData
                // bstateSize: " + bStateSize + " res: " +
                // inputJson.toString(SerializerFeature.WriteMapNullValue));
            } else {
                LOG.warn("MobileAreaProcessFunc MapMobArea error res: " + res);
            }
        } else {
            LOG.debug("MapMobArea readBstate cant find mob : " + mobile);
        }
        return null;
    }

    private static void ProcessData(
            JSONObject inputJson,
            HashMap<String, String> sgMap,
            HashMap<String, String> v1cleanMap,
            HashMap<String, String> mobAreaMAp) {
        try {
            JSONArray phoneCallList = inputJson.getJSONArray("phoneCallList");
            int callSize = phoneCallList.size();
            for (int i = 0; i < callSize; i++) {
                JSONObject callJson = (JSONObject) phoneCallList.get(i);
                if (callJson.containsKey(REMOVEJSONKEY)) {
                    callJson.remove(REMOVEJSONKEY);
                }
                String number = callJson.getString("number");
                number = PhoneRecordDataUtils.forMattedPhoneNumber(number);
                callJson.put("number", number);
                if (number != null) {
                    //                ParamCheck.isNull(number, callJson + " number");
                    //                System.out.println("ProcessData input number:" + number + "
                    // format_number: " + PhoneRecordDataUtils.forMattedPhoneNumber(number));
                    String sgtag = null;
                    String coname = null;
                    String sgcsTag = sgMap.get(number);
                    if (sgcsTag != null) {
                        String[] splits = sgcsTag.split(SPLITWORD);
                        if (splits.length == 2) {
                            sgtag = splits[0];
                            coname = splits[1];
                        } else {
                            LOG.error("ProcessData sgcsTagMap sgcsTag err: " + sgcsTag);
                        }
                    }

                    callJson.put("sgtag", sgtag);
                    callJson.put("coname", coname);

                    String[] addrs = null;
                    if (number != null && number.length() == 11) {
                        String subNumber = number.substring(0, 7);
                        addrs = MapMobArea(subNumber, mobAreaMAp, v1cleanMap);
                        if (addrs != null) {
                            LOG.debug(
                                    "ProcessData MapMobArea returns prov:"
                                            + addrs[0]
                                            + " city: "
                                            + addrs[1]);
                            callJson.put("mob_prov", addrs[0]);
                            callJson.put("mob_city", addrs[1]);
                        }
                    }
                }

                phoneCallList.set(i, callJson);
            }
        } catch (Exception e) {
            LOG.error("ProcessData exception: " + e.toString());
            LOG.error("ProcessData exception input: " + inputJson);
            e.printStackTrace();
        }
    }
}
